package com.xdwanj.retrofittest.fetchr;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.xdwanj.retrofittest.api.FlickrApi;
import com.xdwanj.retrofittest.data.TokenUser;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
//import retrofit2.converter.scalars.ScalarsConverterFactory;

public class FlickrFetcher {
    private final String TAG = "FlickrFetcher";

    private static FlickrFetcher INSTANCE = null;

    private FlickrFetcher() {
        retrofit = new Retrofit.Builder()
                .baseUrl("http://124.93.196.45:10001")
//                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        flickrApi = retrofit.create(FlickrApi.class);
    }

    public static FlickrFetcher getInstance() {
        if (INSTANCE != null) {
            return INSTANCE;
        } else {
            throw new IllegalStateException("FlickFetcher not init");
        }
    }

    public static void initialize() {
        if (INSTANCE == null) {
            INSTANCE = new FlickrFetcher();
        } else {
            throw new IllegalStateException("FlickFetcher is init");
        }
    }

//    ----------------------------------------------------------------

    private final Retrofit retrofit;

    private final FlickrApi flickrApi;


    public LiveData<String> fetchContents() {
        MutableLiveData<String> responseLiveData = new MutableLiveData<>();
        Call<String> call = flickrApi.fetchContents();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d(TAG, "onResponse: Response received");
                responseLiveData.setValue(response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d(TAG, "onFailure: Failed to fetch photos" + t);
            }
        });

        return responseLiveData;
    }

    public LiveData<TokenUser> fetchToken(TokenUser user) {
        MutableLiveData<TokenUser> responseLiveData = new MutableLiveData<>();
        Call<TokenUser> call = flickrApi.fetchToken(user);

        call.enqueue(new Callback<TokenUser>() {
            @Override
            public void onResponse(Call<TokenUser> call, Response<TokenUser> response) {
                Log.d(TAG, "onResponse: ");
                responseLiveData.setValue(response.body());
            }

            @Override
            public void onFailure(Call<TokenUser> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });

        return responseLiveData;
    }
}
